<template>
  <div class="white-list-management">
    <!-- 统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 告警统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="待审核"
          :value="statistics.pending.toString()"
          icon="el-icon-time"
          type="warning"
        />
        <StatisticCard
          label="已确认"
          :value="statistics.confirmed.toString()"
          icon="el-icon-check-circle"
          type="success"
        />
        <StatisticCard
          label="误  报"
          :value="statistics.falsePositive.toString()"
          icon="el-icon-circle-close"
          type="info"
        />
        <StatisticCard
          label="已忽略"
          :value="statistics.ignored.toString()"
          icon="el-icon-minus-circle"
          type="primary"
        />
        <StatisticCard
          label="今日新"
          :value="statistics.todayNew.toString()"
          icon="el-icon-bell"
          type="danger"
        />
        <StatisticCard
          label="总告警"
          :value="statistics.total.toString()"
          icon="el-icon-files"
          type="primary"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 规则列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <DynamicTable
        ref="tableRef"
        :data="list"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        selection-type="multiple"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <template #table-top>
          <div class="action-bar">
            <el-button
              type="primary"
              @click="openBatchReview"
              :disabled="selectedRows.length === 0"
            >
              批量审核
              <span v-if="selectedRows.length > 0">
                (已选: {{ selectedRows.length }} 项)
              </span>
            </el-button>
            <span class="selected-count" v-if="selectedRows.length > 0">
              已选: {{ selectedRows.length }} 项
            </span>
          </div>
        </template>
        <template #risk_level="{ row }">
          <el-tag
            :type="
              row.risk_level === 'critical'
                ? 'danger'
                : row.risk_level === 'high'
                ? 'warning'
                : row.risk_level === 'medium'
                ? 'info'
                : ''
            "
          >
            {{ row.risk_level_name || row.risk_level }}
          </el-tag>
        </template>
        <template #status="{ row }">
          <el-tag
            :type="
              row.review_status === 'pending_review'
                ? 'warning'
                : row.review_status === 'confirmed'
                ? 'success'
                : row.review_status === 'false_positive'
                ? 'info'
                : ''
            "
          >
            {{ row.review_status_name || row.review_status }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-button size="small" @click="openDetailModal(row)" type="info">
            详情
          </el-button>
          <el-button
            :disabled="row.review_status !== 'pending_review'"
            size="small"
            @click="handleOpenReview(row)"
            type="primary"
          >
            审核
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 告警详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :alert="currentDetailRule"
      @review="handleOpenReview"
    />

    <!-- 审核弹窗 -->
    <ReviewModal
      v-model="reviewVisible"
      :alert="currentReviewAlert"
      @reviewed="handleAlertReviewed"
    />

    <!-- 批量审核弹窗 -->
    <el-dialog
      v-model="batchReviewVisible"
      title="批量审核"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-review-dialog">
        <el-alert
          title="批量审核提示"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        >
          已选择 {{ selectedRows.length }} 条告警，请选择审核决策并填写意见
        </el-alert>

        <div
          class="selected-alerts"
          style="max-height: 200px; overflow-y: auto; margin-bottom: 20px"
        >
          <el-tag
            v-for="alert in selectedRows"
            :key="alert.alert_id"
            style="margin: 5px"
          >
            {{ alert.alert_id }} - {{ alert.asset_ip }} -
            {{ alert.risk_level_name }}
          </el-tag>
        </div>

        <el-form :model="batchReviewForm" label-width="80px">
          <el-form-item label="审核决策">
            <el-radio-group v-model="batchReviewForm.decision">
              <el-radio value="confirmed">确认告警</el-radio>
              <el-radio value="false_positive">误报</el-radio>
              <el-radio value="ignored">忽略</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核意见">
            <el-input
              v-model="batchReviewForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见（必填）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="batchReviewVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBatchReview">
          批量提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import DetailModal from "./components/DetailModal.vue";
import ReviewModal from "./components/ReviewModal.vue";
import {
  getAlertList,
  getAlertStatistics,
  getAlertFilterOptions,
  getAlertDetail,
  reviewAlert,
  batchReviewAlerts,
  getAlertReviewHistory,
} from "../../servers";

// 页面状态
const username = ref("张三");
const isFilterExpanded = ref(true);
const loading = ref(false);
const selectedRows = ref<any[]>([]);
const detailVisible = ref(false);
const currentDetailRule = ref<any>({});
const reviewVisible = ref(false);
const currentReviewAlert = ref<any>({});
const batchReviewVisible = ref(false);
const batchReviewForm = reactive({
  decision: "confirmed" as "confirmed" | "false_positive" | "ignored",
  comment: "",
});

// 统计信息
const statistics = reactive({
  pending: 0,
  confirmed: 0,
  falsePositive: 0,
  ignored: 0,
  todayNew: 0,
  total: 0,
});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  scene_type: "",
  review_status: "",
  risk_level: "",
  responsible_person: "",
  department: "",
  start_time: "",
  end_time: "",
  ip_or_keyword: "",
});

// 筛选选项（从接口获取）
const filterOptions = reactive({
  departments: [] as string[],
  responsible_persons: [] as string[],
  scene_types: [] as Array<{ value: string; label: string }>,
  review_statuses: [] as Array<{ value: string; label: string }>,
  risk_levels: [] as Array<{ value: string; label: string }>,
});

// 筛选表单配置（动态从接口获取选项）
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "scene_type",
    name: "场景类型",
    type: "select",
    placeholder: "请选择场景类型",
    params: { clearable: true },
    options: filterOptions.scene_types.map((item) => ({
      label: item.label,
      value: item.value,
    })),
    col: { span: 6 },
  },
  {
    key: "review_status",
    name: "审核状态",
    type: "select",
    placeholder: "请选择审核状态",
    params: { clearable: true },
    options: filterOptions.review_statuses.map((item) => ({
      label: item.label,
      value: item.value,
    })),
    col: { span: 6 },
  },
  {
    key: "risk_level",
    name: "风险等级",
    type: "select",
    placeholder: "请选择风险等级",
    params: { clearable: true },
    options: filterOptions.risk_levels.map((item) => ({
      label: item.label,
      value: item.value,
    })),
    col: { span: 6 },
  },
  {
    key: "responsible_person",
    name: "责任人",
    type: "input",
    placeholder: "请输入责任人",
    col: { span: 6 },
  },
  {
    key: "department",
    name: "部  门",
    type: "select",
    placeholder: "请选择部门",
    params: { clearable: true },
    options: filterOptions.departments.map((dept) => ({
      label: dept,
      value: dept,
    })),
    col: { span: 6 },
  },
  {
    key: "start_time",
    name: "开始时间",
    type: "date",
    placeholder: "请选择开始时间",
    params: {
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      clearable: true,
    },
    col: { span: 6 },
  },
  {
    key: "end_time",
    name: "结束时间",
    type: "date",
    placeholder: "请选择结束时间",
    params: {
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      clearable: true,
    },
    col: { span: 6 },
  },
  {
    key: "ip_or_keyword",
    name: "IP/关键词",
    type: "input",
    placeholder: "请输入IP或关键词",
    col: { span: 6 },
  },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  { label: "告警ID", prop: "alert_id" },
  {
    label: "场景类型",
    prop: "scene_type",
    formatter: (row) => {
      // 优先使用接口返回的场景类型名称
      return row.scene_type_name || row.scene_type || "-";
    },
  },
  { label: "资产IP", prop: "asset_ip", minWidth: 120 },
  { label: "端口", prop: "asset_port", minWidth: 80, align: "center" },
  {
    label: "风险",
    prop: "risk_level",
    slot: "risk_level",
  },
  {
    label: "状态",
    prop: "status",
    slot: "status",
  },
  { label: "责任人", prop: "responsible_person", minWidth: 100 },
  {
    label: "检测时间",
    prop: "detected_time",
    minWidth: 160,
    formatter: (row) => {
      if (!row.detected_time) return "-";
      return row.detected_time.replace("T", " ").substring(0, 19);
    },
  },
  {
    label: "操作",
    width: 140,
    fixed: "right",
    slot: "action",
  },
];

// 表格数据
const list = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 表格引用
const tableRef = ref<DynamicTableInstance>();

// 获取筛选选项
const fetchFilterOptions = async () => {
  try {
    const { data } = await getAlertFilterOptions();
    if (data) {
      filterOptions.departments = data.departments || [];
      filterOptions.responsible_persons = data.responsible_persons || [];
      filterOptions.scene_types = data.scene_types || [];
      filterOptions.review_statuses = data.review_statuses || [];
      filterOptions.risk_levels = data.risk_levels || [];
    }
  } catch (error: any) {
    console.error("获取筛选选项失败:", error);
    // 筛选选项获取失败不影响主流程，只打印错误
  }
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const params: any = {};
    if (filterForm.start_time) {
      params.start_time = `${filterForm.start_time} 00:00:00`;
    }
    if (filterForm.end_time) {
      params.end_time = `${filterForm.end_time} 23:59:59`;
    }

    const { data } = await getAlertStatistics(params);
    if (data) {
      statistics.pending = data.by_review_status?.pending_review || 0;
      statistics.confirmed = data.by_review_status?.confirmed || 0;
      statistics.falsePositive = data.by_review_status?.false_positive || 0;
      statistics.ignored = data.by_review_status?.ignored || 0;
      statistics.todayNew = data.today_new_count || 0;
      statistics.total = data.total_count || 0;
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
    // 统计数据获取失败不影响主流程，只打印错误
  }
};

// 获取告警列表
const fetchList = async (values: any = {}) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      ...values,
    };

    // 添加筛选条件
    // if (filterForm.scene_type) {
    //   params.scene_type = filterForm.scene_type;
    // }
    // if (filterForm.review_status) {
    //   params.review_status = filterForm.review_status;
    // }
    // if (filterForm.risk_level) {
    //   params.risk_level = filterForm.risk_level;
    // }
    // if (filterForm.responsible_person) {
    //   params.responsible_person = filterForm.responsible_person;
    // }
    // if (filterForm.department) {
    //   params.department = filterForm.department;
    // }
    // if (filterForm.start_time) {
    //   params.start_time = `${filterForm.start_time} 00:00:00`;
    // }
    // if (filterForm.end_time) {
    //   params.end_time = `${filterForm.end_time} 23:59:59`;
    // }
    // if (filterForm.ip_or_keyword) {
    //   params.keyword = filterForm.ip_or_keyword;
    // }

    // 排序
    params.sort_by = "detected_time";
    params.sort_order = "desc";

    const { data } = await getAlertList(params);
    if (data) {
      list.value = data.items || [];
      pagination.total = data.pagination?.total || data.total || 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取告警列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchList();
};

const handleSearch = (values: any) => {
  console.log(values, "valuesvaluesvaluesvalues");

  pagination.currentPage = 1;
  fetchList(values);
};

const handleExport = () => {
  ElMessage.success("Excel导出成功");
};

// 表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList();
};

// 弹窗控制
const openDetailModal = async (row: any) => {
  try {
    loading.value = true;
    const { data } = await getAlertDetail({ alert_id: row.alert_id });
    if (data) {
      currentDetailRule.value = data;
      detailVisible.value = true;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取告警详情失败");
  } finally {
    loading.value = false;
  }
};

// 打开批量审核弹窗
const openBatchReview = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要审核的告警");
    return;
  }

  // 检查是否都是待审核状态
  const hasPending = selectedRows.value.every(
    (alert) => alert.review_status === "pending_review"
  );

  if (!hasPending) {
    ElMessage.warning("只能审核待审核状态的告警");
    return;
  }

  batchReviewForm.decision = "confirmed";
  batchReviewForm.comment = "";
  batchReviewVisible.value = true;
};

// 提交批量审核
const submitBatchReview = async () => {
  if (!batchReviewForm.comment.trim()) {
    ElMessage.warning("请填写审核意见");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量${getDecisionText(batchReviewForm.decision)} ${
        selectedRows.value.length
      } 条告警吗？`,
      "确认批量审核",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const alertIds = selectedRows.value.map((alert) => alert.alert_id);

    const result = await batchReviewAlerts({
      alert_ids: alertIds,
      review_decision: batchReviewForm.decision,
      review_comment: batchReviewForm.comment,
    });

    if (result?.data) {
      const { success_count, failed_count, total_count, failed_items } =
        result.data;

      if (failed_count === 0) {
        ElMessage.success(`批量审核成功！共处理 ${total_count} 条告警`);
      } else {
        ElMessage.warning(
          `批量审核完成！成功 ${success_count} 条，失败 ${failed_count} 条`
        );

        if (failed_items && failed_items.length > 0) {
          const failedMsg = failed_items
            .map((item: any) => `${item.alert_id}: ${item.reason}`)
            .join("\n");

          ElMessageBox.alert(failedMsg, "失败详情", { type: "error" });
        }
      }
    } else {
      ElMessage.success(result?.message || "批量审核成功");
    }

    selectedRows.value = [];
    batchReviewVisible.value = false;
    fetchList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量审核失败");
    }
  } finally {
    loading.value = false;
  }
};

// 获取决策文本
const getDecisionText = (
  decision: "confirmed" | "false_positive" | "ignored"
): string => {
  const map: Record<string, string> = {
    confirmed: "确认",
    false_positive: "标记为误报",
    ignored: "忽略",
  };
  return map[decision] || "";
};

// 打开审核弹窗
const handleOpenReview = (alert: any) => {
  currentReviewAlert.value = alert;
  reviewVisible.value = true;
  detailVisible.value = false;
};

// 告警审核后的回调
const handleAlertReviewed = () => {
  fetchList();
  fetchStatistics();
};

// 初始化
onMounted(() => {
  fetchFilterOptions();
  fetchStatistics();
  fetchList();
});
</script>

<style scoped lang="scss">
.white-list-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .navbar-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .navbar-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #333;
      }

      .user-info {
        color: #666;
        font-size: 14px;
      }
    }
  }

  .stats-card,
  .filter-card,
  .action-bar-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .filter-content {
    padding: 5px 0;
  }

  .filter-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;

    .action-btn {
      margin-right: 10px;
    }

    .export-btn {
      margin-left: auto;
    }
  }

  .action-bar {
    display: flex;
    align-items: center;
    gap: 10px;

    .selected-count {
      margin-left: auto;
      color: #666;
      font-size: 14px;
    }
  }
}
</style>
